package com.zimin.cloud.wiki.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zimin.cloud.mine.pojo.wiki.business.DocBO;
import com.zimin.cloud.mine.pojo.wiki.view.DocVO;
import com.zimin.cloud.wiki.mapper.DocMapper;
import com.zimin.cloud.wiki.pojo.entity.Doc;
import com.zimin.cloud.wiki.service.IDocService;
import com.zimin.common.exception.GraceException;
import com.zimin.common.utils.BeanUtils;
import com.zimin.common.utils.StringUtils;
import com.zimin.shared.enums.ResponseStatusEnum;
import com.zimin.shared.pojo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 文档 服务实现类
 * </p>
 *
 * @author zimin
 * @since 2021-10-27 21:02
 */
@Service
public class DocServiceImpl extends ServiceImpl<DocMapper, Doc> implements IDocService {

    @Autowired
    private DocMapper docMapper;

    @Override
    public PageVO<DocVO> list(Page page, DocBO docBO) {
        Page<Doc> docPage = page(page, Wrappers.<Doc>lambdaQuery()
                .like(StringUtils.isNotEmpty(docBO.getName()), Doc::getName, docBO.getName()));
        List<Doc> records = docPage.getRecords();
        List<DocVO> docVOS = BeanUtils.listEntityToView(records, DocVO.class);
        return pageToPageVO(docPage, docVOS);
    }

    @Override
    public List<DocVO> list(DocBO docBO) {
        List<Doc> list = list(Wrappers.<Doc>lambdaQuery()
                .eq(Doc::getEbookId, docBO.getEbookId())
                .like(StringUtils.isNotEmpty(docBO.getName()), Doc::getName, docBO.getName())
                .orderByAsc(Doc::getSort));
        return BeanUtils.listEntityToView(list, DocVO.class);
    }


    @Override
    public boolean save(DocBO docBO) {
        var doc = new Doc();
        BeanUtils.copyProperties(docBO, doc);
        boolean flag = save(doc);
        if(flag){
            docBO.setId(doc.getId());
        }
        return flag;
    }

    @Override
    public boolean updateById(DocBO docBO) {
        var doc = new Doc();
        BeanUtils.copyProperties(docBO, doc);
        return updateById(doc);
    }

    @Override
    public boolean removeByIds(String ids) {
        if (StringUtils.isEmpty(ids)) {
            GraceException.display(ResponseStatusEnum.FAILED);
        }
        return removeByIds(Arrays.asList(ids.split(",")));
    }

    @Override
    public DocVO getDocById(String id) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("doc.id", id);
        return docMapper.getDocContent(wrapper);
    }


}
